<?php
/**
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/12/5
 * Time: 13:34
 */
namespace app\api\controller\finance;
use think\Controller;
use app\api\controller\common\ApiBase;
use Think\Db;
use app\api\model\Admin as AdminModel;

class Financebilling extends ApiBase
{
    protected $admin;
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('CompanyFollow');
    }

    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }

    /**
     * 私海列表
     * @param member_id,public_id,sale_id
     */
    public function index(){
        if (request()->isPost()) {
            $post = input('post.');
            $page = isset($post['page']) && $post['page'] != '' ? $post['page'] : 1;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            $keyWord = isset($post['keyWord']) && $post['keyWord'] != '' ? $post['keyWord'] : null;
            $status = isset($post['status']) && $post['status'] != '' ? $post['status'] : 0;
            if(empty($exhibition_id)){
                return json(['code'=>0,'msg'=>'展会数据有误']);
            }
            $tabName=$this->getTabName($exhibition_id);
            $param=" and p.exhibition_id=".$exhibition_id." and p.is_delete=0 ";
            if($status == 1){
                $param.=" and p.billing_status=1 ";
            }else if($status == 2){
                $param.=" and p.billing_status=2 ";
            }else{
                $param.=" and p.billing_status>=1 ";
            }
            if($keyWord){
                $param.=" and p.company_id in (select id from crm_".$tabName." where company_name LIKE '%$keyWord%') ";
            }
            $sql="SELECT p.*,a.realname,c.company_name as zs_company_name FROM crm_billing as p ";
            $sql.=" LEFT JOIN crm_".$tabName." as c ON c.id=p.company_id";
            $sql.=" LEFT JOIN crm_admin as a ON a.id=c.member_id";
            $sql.=" where 1=1 $param";
//            $sql.=" order by p.billing_status asc";
            $sql.=" order by p.id desc";
            $sql.=" limit ".($page-1)*$pageSize.",$pageSize";
            $list=Db::query($sql);
            $sql1=" select count(p.id) as count1 ";
            $sql1.=" from crm_billing as p where 1=1 $param ";
            $total1=Db::query($sql1);
            $total=$total1[0]['count1']; //st
            foreach ($list as $val){
                $val['create_time']=$val['submit_time']?$val['submit_time']:$val['create_time'];
            }
            return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     * 添加开票记录
     */

    public function check(){
        if (request()->isPost()) {
            $post = input('post.');
            $ids = isset($post['ids']) && $post['ids'] != '' ? $post['ids'] : '';
            if(!$ids){
                return json(array('code' => '0', 'msg' => '数据错误'));
            }
            $res=db('billing')->where(['id'=>['in',$ids]])->select();
            $is = true;
            $msg = '';
            //首先进行数据验证
            foreach ($res as $val){
                if($val['billing_status']==2){
                    $is=false;
                    $msg=$val['id'].'此数据已审核通过,操作失败!';
                    break;
                }
            }
            if(!$is){
                return json(['code'=>0,'msg'=>$msg]);
            }

            $billing_time = isset($post['billing_time']) && $post['billing_time'] != '' ? $post['billing_time'] : '';
            $billing_number = isset($post['billing_number']) && $post['billing_number'] != '' ? $post['billing_number'] : '';
            $data['billing_time']=$billing_time?strtotime($billing_time."  00:00:00"):'';
            $data['billing_number']=$billing_number;
            $data['update_time']=time();
            $data['billing_status']=2;
            $res=db('billing')->where(['id'=>['in',$ids]])->update($data);
            if(!$res){
                return json(array('code' => '0', 'msg' => '操作失败'));
            }
            return json(array('code' => '1', 'msg' => '操作成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     * 撤回开票记录
     */

    public function isCheck(){
        if (request()->isPost()) {
            $post = input('post.');
            $ids = isset($post['ids']) && $post['ids'] != '' ? $post['ids'] : '';
            if(!$ids){
                return json(array('code' => '0', 'msg' => '数据错误'));
            }
            $res=db('billing')->where(['id'=>['in',$ids]])->select();
            $is = true;
            $msg = '';
            //首先进行数据验证
            foreach ($res as $val){
                if($val['billing_status']==1){
                    $is=false;
                    $msg=$val['id'].'此数据未审核通过,操作失败!';
                    break;
                }
            }
            if(!$is){
                return json(['code'=>0,'msg'=>$msg]);
            }
            $data['billing_time']='';
            $data['billing_number']='';
            $data['update_time']=time();
            $data['billing_status']=0;
            $res=db('billing')->where(['id'=>['in',$ids]])->update($data);
            if(!$res){
                return json(array('code' => '0', 'msg' => '操作失败'));
            }
            return json(array('code' => '1', 'msg' => '操作成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function export(){
        if (request()->isPost()) {
            $post = input('post.');
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            if(empty($exhibition_id)){
                return json(['code'=>0,'msg'=>'展会数据有误']);
            }
            $tabName=$this->getTabName($exhibition_id);
            $param=" and p.exhibition_id=".$exhibition_id." and p.is_delete=0 and p.billing_status>=1";
            $sql="SELECT p.*,c.company_name as base_company_name FROM crm_billing as p ";
            $sql.=" LEFT JOIN crm_".$tabName." as c ON c.id=p.company_id";
            $sql.=" where 1=1 $param";
//            $sql.=" order by p.billing_status asc";
            $sql.=" order by p.id asc";
            $list=Db::query($sql);
            if(count($list)==0){
                return json(array('code' => '0', 'msg' => '暂无数据'));
            }
            foreach ($list as &$vv){
                $vv['billing_type_name']=($vv['billing_type'] == 1?'增值税普通发票':'增值税专用发票');
                $vv['billing_mode_name']=($vv['billing_mode'] == 1?'纸质发票':'电子发票');
                $vv['billing_status_name']=($vv['billing_status'] == 1?'未开票':'开票完成');
                $vv['tax_number']=$vv['tax_number']."\t";
                $vv['bank_number']=$vv['bank_number']."\t";
                $vv['billing_time_date']=$vv['billing_time']?date('Y-m-d',$vv['billing_time']):'';
            }
            unset($vv);
            $columns = array(
                array('title' => 'ID', 'field' => 'id', 'width' => 12,'code'=>'A'),
                array('title' => '发票类型', 'field' => 'billing_type_name', 'width' => 12,'code'=>'B'),
                array('title' => '发票抬头', 'field' => 'company_name', 'width' => 12,'code'=>'C'),
                array('title' => '税务登记号', 'field' => 'tax_number', 'width' => 12,'code'=>'D'),
                array('title' => '开户银行', 'field' => 'bank_title', 'width' => 12,'code'=>'E'),
                array('title' => '银行账号', 'field' => 'bank_number', 'width' => 12,'code'=>'F'),
                array('title' => '企业电话', 'field' => 'company_phone', 'width' => 24,'code'=>'G'),
                array('title' => '企业地址', 'field' => 'company_address', 'width' => 24,'code'=>'H'),
                array('title' => '开票方式', 'field' => 'billing_mode_name', 'width' => 24,'code'=>'I'),
                array('title' => '开票金额（元）', 'field' => 'billing_money', 'width' => 24,'code'=>'G'),
                array('title' => '收件人姓名', 'field' => 'receiving_name', 'width' => 24,'code'=>'H'),
                array('title' => '收件人电话', 'field' => 'receiving_phone', 'width' => 24,'code'=>'K'),
                array('title' => '收件人地址', 'field' => 'receiving_address', 'width' => 24,'code'=>'L'),
                array('title' => '开票状态', 'field' => 'billing_status_name', 'width' => 24,'code'=>'M'),
                array('title' => '开票时间', 'field' => 'billing_time_date', 'width' => 24,'code'=>'N'),
                array('title' => '票号', 'field' => 'billing_number', 'width' => 24,'code'=>'O'),
                array('title' => '所属展商', 'field' => 'base_company_name', 'width' => 24,'code'=>'O'),
            );
            $title = "票务明细";
            $filename = $title . date('Y-m-d-H-i', time()) . ".xls";
            return json(['code'=>1,'msg'=>'操作成功','data'=>['columns'=>$columns,'filename'=>$filename,'list'=>$list]]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


}
